package com.bjpowernode.interceptors;

import com.bjpowernode.exception.MyException;
import com.bjpowernode.services.UserServices;
import com.bjpowernode.tools.MyTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    UserServices userServices;


    //这里需要根据情况判定cookie
    //准备拦截
    //return true;放行
    //return false;不能到达请求地址

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("1——开始请求：" + request.getRequestURI());
        HttpSession session = request.getSession();

        if (session.getAttribute("user") == null) {
            System.out.println("2-1——拦截住了：" + request.getRequestURI());

            MyTools.loginCookies(request, userServices, () -> {
                throw new MyException("需要登录用户才能使用该功能，请登录");
            });


        }
        return true;
    }

    //准备响应
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("3——响应之前处理：" + request.getRequestURI());
    }

    //响应结束了
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("4——响应结束：" + request.getRequestURI());
    }
}
